//let ErrorUtils = require('../utils/error/ErrorUtils');
//const {infoLogger, errorLogger} = require('../config').logger;
let rp = require('request-promise');
let redis = require('../redis');
let config = require('../config');
const wechatUrl = 'https://api.weixin.qq.com/sns/jscode2session';

class WechatService {
    /**
     *获取redis accesstoken
     */
    static getRedisAccessToken() {
        return redis.get(config.redis.tokenKey);
    }

    /**
     *设置redis accesstoken
     */
    static setRedisAccessToken(token) {
        let accessTokenKey = config.redis.tokenKey;
        let expire = token.expires_in || config.redis.expire;
        return redis.setex(accessTokenKey, expire, token.access_token);
    }

    static async getAccessToken() {
        let accessToken = await WechatService.getRedisAccessToken();
        if (!accessToken) {
            let appid = config.wechat.appId;
            let appsecret = config.wechat.secret;
            let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`;
            let token = await rp(url);
            if (token) {
                token = JSON.parse(token);
                accessToken = token.access_token;
                await WechatService.setRedisAccessToken(token);
            } else {
                return false;
            }
        }
        return accessToken;
    }
    /**
     * 获取sessionKey
     * @param code
     */
    static getSessionKey(code) {
        let url = `${wechatUrl}?appid=${config.wechat.appId}&secret=${config.wechat.secret}&js_code=${code}&grant_type=authorization_code`;
        return rp({
            uri: url,
            method: 'GET',
            json: true,
        });
    }
}

module.exports = WechatService;
